package com.example.mvvmrxjavaokhttpretrofit.net;


import com.example.mvvmrxjavaokhttpretrofit.constants.HttpResponseCode;
import com.example.mvvmrxjavaokhttpretrofit.net.exception.ExceptionHandle;
import com.example.mvvmrxjavaokhttpretrofit.net.exception.ResponseThrowable;
import com.example.mvvmrxjavaokhttpretrofit.utils.NetworkUtil;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class RdSubscriber implements Observer {

    private String requestType;

    public RdSubscriber(String requestType) {
        this.requestType = requestType;
    }


    @Override
    public void onSubscribe(Disposable disposable) {
        if (!NetworkUtil.isNetworkAvailable()) {
            onError(new ResponseThrowable("no netword",
                    ExceptionHandle.ERROR.NETWORK_DISABLE));
            if (!disposable.isDisposed()) {
                disposable.dispose();
            }
        }
    }


    @Override
    public void onComplete() {
    }

    /**
     * @param o
     */
    @Override
    public void onNext(Object o) {
        if (o instanceof BaseResponse) {
            BaseResponse baseResponse = (BaseResponse) o;
            switch (baseResponse.getCode()) {
                case HttpResponseCode.SUCCESS://执行成功
                case HttpResponseCode.NODATAS://列表数据为空
                    onSuccess(baseResponse.getCode(), requestType, baseResponse.getData());
                    break;
                case HttpResponseCode.USER_UNLOGIN://用户未登录,跳登录界面
                case HttpResponseCode.TOKEN_DISABLED://Token失效,跳登录界面
                case HttpResponseCode.LOGIN_AT_ANORTHER1://在其他设备登录,跳登录界面
                case HttpResponseCode.LOGIN_AT_ANORTHER2://在其他设备登录,跳登录界面

                    break;
                default://其他情况
                    onFail(baseResponse.getCode(), requestType, baseResponse.getMsg(), baseResponse.getData());
            }
        } else {
            onFail(0, requestType, "数据异常", o);
        }
    }

    @Override
    public void onError(Throwable e) {
        ResponseThrowable responseThrowable = ExceptionHandle.handleException(e);
        onFail(responseThrowable.code, requestType, responseThrowable.message, null);
    }



    protected abstract void onSuccess(int responCode, String responType, Object data);

    protected abstract void onFail(int responCode, String responType, String message, Object data);

}
